<template>
  <div id="echartsMap">
    <table style="height:100%;width:100%;">
      <tr>
      <td id="tdMap" rowspan="2">
           <div id="echartsProvince"></div>
      </td>
      <td>
        <div id="decContent">
            <h2 style="margin-left:10px;">省区介绍</h2>
            <ul class="login-info-list" style="margin-left:10px;">
              <li class="login-info-item" v-for="(item,index) in listDec" :key="index">
                {{item}}
              </li>
            </ul>
        </div>
      </td>
        </tr>
        <tr>
          <td>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="园区流量排名" name="third">
                <div id="echartsRigthTop5"></div>
              </el-tab-pane>
              <el-tab-pane label="实时曲线" name="first">
                <div id="echartsRigthBottom"></div>
              </el-tab-pane>
              <el-tab-pane label="历史曲线" name="second">
                <div id="echartsRigthTop"></div>
              </el-tab-pane>
              
            </el-tabs>
          </td>
          </tr>
    </table>
    <el-dialog id="edialog" title= "工业园列表" :visible.sync = "dialogVisible" width = "20%">
        <table>
        <tr>
          <td style="width:200px;">
            <el-select v-model="valuePark" placeholder="请选择工业园" @change="viewDetail">
              <el-option v-for="item in optionPark" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
           
          </td>
        </tr>
      </table>
    </el-dialog>
  </div>
</template>

<script>
import optionAnhui from '../../../assets/js/map-option-anhui.js'
import echartsRigthTopOption from '../../../assets/js/echartsRightTop.js'
import echartsRigthBottomOption from '../../../assets/js/echartsRightBottom.js'

import{
  geiIdByCityName
} from '@/util/provinceAndCity';
import{
  
  getListByCityId
} from '@/api/bus/sensor/industry';
import {
  getObj,
  // getSensorData,
  // sensorFlowProvinceData,
  // getSensorFlowProvinceData
  getCityListByProvinceId
} from '@/api/bus/sensor/province';
import{
    getLatestSensorList,
  getSensorDataForPeriodOfTime,
  getTop5StaticData,
   getTop5PointData
} from '@/api/bus/sensor/sensorData';
require('echarts/map/js/province/anhui')

export default {
  name: 'echartsMap',
  data () {
    return {
        // optionPark:[
        //   {value:'1',label:'莆田工业园'},
        //   {value:'2',label:'珠海工业园'}
        //   ],
        optionPark:[],
        valuePark    : '',
        msg          : '',
        dialogVisible: false,
        activeName: 'third',
        list         : null,
        listDec   : [],
        provinceId:'340000',
        cityPointData:[],
        provincePointOneHourData:[],
        myOneDayChart:{},
        myOneHourChart:{},
        myChart:{},
        cityList:[],
        dataXAxis:[],
        dataYAxis:[],
        dataLegend:[],
        top5DataXAxis:[],
        top5DataYAxis:[],
        dataMax:0,
        series:[],

        dataOneHourXAxis:[],
        dataOneHourYAxis:[],
        dataOneHourLegend:[],
        top5OneHourDataXAxis:[],
        top5OneHourDataYAxis:[],
        dataOneHourMax:0,
        OneHourseries:[],
    }
  },
  created() {
     
   
    
  },
  mounted(){
    this.drawProvinceMap(document.getElementById('routerBase').offsetHeight);
    
    
     
  },
  methods: {
          getCityPointData(){
            //全省时点累计流量
            // console.log('查询全省各市各时点的数据')
              getLatestSensorList("340000","PROVINCE").then(response=>{
                // console.log(response);
                  this.refreshEchartsData(response.data);
              });
          },
          refreshLineChartData(responseDatas){
            let that = this;
            this.provincePointOneHourData=[];
            that.top5OneHourDataXAxis=[];
            that.top5OneHourDataYAxis=[];
            that.OneHourseries=[];
            if(responseDatas.length != 0){
               for (let index = 0; index < responseDatas.data.length; index++) {
                var vt = responseDatas.data[index];
                var vname = vt[0].searchId;
                that.dataOneHourLegend.push(vname);
                var dataYAxis=[];
                for(let j=0;j<vt.length;j++){
                  var vtt = vt[j];
                  if(index==0)
                  {
                      that.top5OneHourDataXAxis.push(vtt.timePoint);
                  }
                  
                  dataYAxis.push(vtt.data);
                }
                that.OneHourseries.push({
                  name:vname,
                  type:'line',
                  data : dataYAxis
                })
              }
            }
            
            this.myOneHourChart.setOption({
                legend: {
                    data: that.dataOneHourLegend,
                },
                xAxis:{
                  data:that.top5OneHourDataXAxis,
                },
                dataZoom: [{
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 90,
                    end: 100
                }, {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 0,
                    end: 100
                }],
                series:that.OneHourseries
                })
          },
          getNowFormatDate(ifOneHour,ifOneDay){

                  var timestamp = Date.parse(new Date());
                  var subOneHour = ifOneHour*1*60*60*1000;
                  var subOneDay = ifOneDay*7*24*60*60*1000;

                  timestamp=timestamp-subOneHour-subOneDay;
                  var unixtimestamp = new Date(parseInt(timestamp));
                  var year = 1900 + unixtimestamp.getYear();
                  var month = "0" + (unixtimestamp.getMonth() + 1);
                  var date = "0" + (unixtimestamp.getDate()-ifOneDay*7);
                  var hour = "0" + (unixtimestamp.getHours()-ifOneHour*1);
                  var minute = "0" + unixtimestamp.getMinutes();
                  var second = "0" + unixtimestamp.getSeconds();
                  return year + "-" + month.substring(month.length-2, month.length)  + "-" + date.substring(date.length-2, date.length)
                      + " " + hour.substring(hour.length-2, hour.length) + ":"
                      + minute.substring(minute.length-2, minute.length) + ":"
                      + second.substring(second.length-2, second.length);
          },
          refreshEchartsData(response){
                let that = this;
                this.cityPointData=[];
                for (let index = 0; index < response.length; index++) {
                    var vt = response[index];
                    var name =  that.getNameById(vt.provinceId);
                    this.cityPointData.push({
                        name :name,
                        value: vt.data
                        })
                }
                // console.log(this.cityPointData);
               this.myChart.setOption({
                series:[{
                  data : this.cityPointData
                }]
              })
          },
          getNameById(id){
             var val = '';
              for (let index = 0; index < this.cityList.length; index++) {
                var  vt = this.cityList[index];
                if(vt.id == id)
                {
                  // console.log(vt.name);
                  val = vt.name+"市";
                  break;
                }
              }
              return val;
          },
          viewDetail(){
          this.$router.push({
              path:'/bus/industry/detail',
              components:'views/bus/industry/detail',
              query:{
                'industryId':this.valuePark,
              }
            });
          },
          //tab标签页的点击事件
          handleClick(tab, event) {
            if(tab.name == 'first')
            {
              setTimeout(() => {
                this.drawBottom();
              }, 500);
            }
            else if(tab.name == 'second')
            {
              setTimeout(() => {
                   this.drawTop();
              }, 100);
               
            }
            else if( tab.name == 'third')
            {
              setTimeout(() => {
                this.drawTop5();
              }, 100);
                
            }
          },
          getProvinceOnDayData(responseDatas){
            console.log(responseDatas);

            //刷新当前时点24小时流量图
            let that = this;
            that.provincePointOneDayData=[];
            that.series=[];
            that.top5DataXAxis=[];
            that.top5DataYAxis=[];
            if(responseDatas.length != 0){
               for (let index = 0; index < responseDatas.data.length; index++) {
                var vt = responseDatas.data[index];
                that.dataLegend.push(vt[0].searchName);
                var yAxis=[];
                for(let j=0;j<vt.length;j++){
                  var vtt = vt[j];
                  if(index == 0)
                  {
                    that.top5DataXAxis.push(vtt.timePoint.substring(11,16));
                  }
                  
                  yAxis.push(vtt.data);
                }
                that.series.push({
                  name:vt[0].searchName,
                  type:'line',
                  data : yAxis
                })
              }
            }
            this.myOneDayChart.setOption({
                legend: {
                    data: that.dataLegend,
                },
                xAxis:{
                  data:that.top5DataXAxis,
                },
                dataZoom: [{
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 90,
                    end: 100
                }, {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'empty',
                    start: 0,
                    end: 100
                }],
                series:that.series
                })
          },
          showDialog(cityName){
              this.dialogVisible = true;
              var cityId = geiIdByCityName(cityName)
              this.optionPark=[];
              getListByCityId(cityId).then(response=>{
                for (let index = 0; index < response.data.length; index++) {
                  var vt = response.data[index];
                  this.optionPark.push(
                  {value:vt.id,
                    label:vt.industryName}
                )
                }
              });
          },
          drawTop5(){
            let that       = this;
            that.dataXAxis=[];
            that.dataYAxis=[];
            getTop5PointData("340000","PROVINCE").then(response=>{
                 for (let index = 0; index < response.data.length; index++) {
                  var vt = response.data[index];
                  that.dataXAxis.push(Number(vt.data));
                  that.dataYAxis.push(vt.searchName);
                  if(that.dataMax < Number(vt.data))
                  {
                    that.dataMax = Number(vt.data)/0.9;
                  }
                } 
                 that.chartTop5 = that.$echarts.init(document.getElementById('echartsRigthTop5'));
                that.chartTop5.setOption({
                    color: ['#3398DB'],
                    title: {
                        text: '各省流量排行Top5',
                        //textStyle: {
                        //    color: '#fff'
                        //}
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                    },
                    /*legend: {
                        data: [date]
                    },*/
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '2%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        min: 0,
                        max: that.dataMax,
                        axisLabel: {
                            formatter: '{value}',
                            textStyle: {
                                //color: '#fff',  
                                fontWeight: '80'
                            }
                        }
                    },
                    yAxis: {
                        type: 'category',
                        // data: ['湖北省', '湖南省', '河南省', '安徽省', '浙江省', '山东省', '广东省'],
                        data:that.dataYAxis,
                        axisLabel: {
                            show: true,
                            interval: 0,
                            rotate: 0,
                            margin: 10,
                            inside: false,
                            textStyle: {
                                //color: '#fff',
                                fontWeight: '50'
                            }
                        }
                    },
                    series: [{
                        type: 'bar',
                        label: {
                            normal: {
                                show: true,
                                // formatter: '{c}',
                                formatter: function(v) {
                                    var val = v.data;
                                    if (val == 0) {
                                        return '';
                                    }
                                    return val;
                                },
                                color: '#fff'
                            }
                        },
                        // data: [22, 33, 44, 55, 66, 77, 88]
                        data:that.dataXAxis
                    }]
                });
              });
              
           
           
          },
          drawTop(){
            let that       = this;
             var chartBottom = document.getElementById('echartsRigthTop');
            chartBottom.style.width = document.body.clientWidth*0.25+"px"
            this.myOneDayChart = that.$echarts.init(document.getElementById('echartsRigthTop'));
            this.myOneDayChart.setOption({
                title: {
                    text: '省流量数据'
                },
                legend:{
                  padding:30,
                },
                tooltip: {
                    trigger  : 'axis',
                    // formatter: function (params) {
                    //  console.log(params[0]);
                    //  return params = params[0].seriesId+ '\n'+params[0].seriesName + '---' +parseInt( params[0].data)+'\n';
                    // },
                    axisPointer: {
                        animation: false,
                        type     : 'none',
                    },
                    extraCssText: 'width:220px; white-space:pre-wrap'
                },
                //解决Y轴显示不全的情况
                grid: {
                    left: 60
                },
                xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type       : 'value',
                    boundaryGap: [0, '100%'],
                    splitLine  : {
                        show: false
                    },
                    

                },
                series: [
                {
                    name     : '省当前时点流量图',
                    type     : 'line',
                    itemStyle: {
                      normal : {
                        lineStyle:{
                          color: 'red'
                        }
                      }
                    },
                    showSymbol    : false,
                    hoverAnimation: false,
                    data          :[]
                }
                ]
             });

             var vt = this.getNowFormatDate(0,0);
             var vtOneDayBefore = this.getNowFormatDate(0,1);

             //全省当前时点24小时的流量累计
              getTop5StaticData("340000","PROVINCE","DAY",vtOneDayBefore,vt).then(response=>{
                  this.getProvinceOnDayData(response);
              });
             
          },

          drawProvinceMap(height) {
            let that = this;
            document.getElementById('echartsProvince').style.height = height*0.9+'px';
            this.myChart  = this.$echarts.init(document.getElementById('echartsProvince'));
            this.myChart.setOption(optionAnhui);

            that.getProvinceInfo();
            setTimeout(() => {
              that.getCityPointData();
            }, 100);
            
            //调用数据图的界面
            setTimeout(() => {
              that.drawTop5();
            }, 100);
            
            

            //注册点击事件
            this.myChart.on('click', function (params) {
              that.showDialog(params.data.name);
            });
            
            
            
            
            
          },
          getProvinceInfo(){
            //获取省区信息描述
            getObj(this.provinceId).then(response => {
              this.listDec.push(response.data.provinceType);
            });
            getCityListByProvinceId(this.provinceId).then(response=>{
              this.cityList =[];
              for (let index = 0; index < response.data.length; index++) {
                  var vt = response.data[index];
                  this.cityList.push({
                      id : vt.id,
                      name:vt.cityName
                      })
              }

            })
          },
          drawBottom(){
            let that          = this;
             var chartBottom = document.getElementById('echartsRigthBottom');
            chartBottom.style.width = document.body.clientWidth*0.25+"px"

            this.myOneHourChart = that.$echarts.init(document.getElementById('echartsRigthBottom'));
            this.myOneHourChart.setOption({
               title: {
                    text: '省当前时点流量图'
                },
                // legend:{
                //   data:['压力传感数据','热力传感数据'],
                // },
                tooltip: {
                    trigger  : 'axis',
                    // formatter: function (params) {
                     
                    //  return params = params[0].seriesName+ '\n'+params[0].data.value[0] + '---' +parseInt( params[0].data.value[1])+'\n';
                    // },
                    axisPointer: {
                        animation: false,
                        type     : 'none',
                    },
                    extraCssText: 'width:220px; white-space:pre-wrap'
                },
                //解决Y轴显示不全的情况
                grid: {
                    left: 60
                },
                xAxis: {
                    type     : 'category',
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type       : 'value',
                    boundaryGap: [0, '100%'],
                    splitLine  : {
                        show: false
                    },
                    

                },
                series: [
                {
                    name     : '省当前时点流量图',
                    type     : 'line',
                    itemStyle: {
                      normal : {
                        lineStyle:{
                          color: 'red'
                        }
                      }
                    },
                    showSymbol    : false,
                    hoverAnimation: false,
                    data          : []
                }
                ]
             }
             );
             var vt = this.getNowFormatDate(0,0);
            // var vtOneDayBefore = this.this.getNowFormatDate(0,1);
            var vtOneHourBefore = this.getNowFormatDate(1,0);
            //全国当前时点一小时的流量累计
            // getSensorDataForPeriodOfTime("340000","PROVINCE",vtOneHourBefore,vt).then(response=>{
            //     this.refreshLineChartData(response);
            // });
            getTop5StaticData("340000","PROVINCE","REAL",vtOneHourBefore,vt).then(response=>{
                  if(response == null || response.data.length<1)
                  {
                    alert('未能获取到相关数据');
                    return;
                  }
                  if(response.data.length>0)
                  {
                        this.refreshLineChartData(response);
                  }
                 
              });
          },
        }
        
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
 @import '../../../styles/province.scss';
 
    #echartsRigthTop5{
    width        : 90%;
    height       : 230px;
    border-radius: 5px;
    box-sizing   : border-box;
    background   : #fff;
    overflow     : hidden;
  }
 
</style>